package com.chookss.home.publish;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.ArrayMap;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.FileProvider;

import com.aliyun.svideo.common.utils.NetUtils;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bumptech.glide.Glide;
import com.chookss.BuildConfig;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.UploadEntity;
import com.chookss.mine.personal.upload.UploadFileService;
import com.chookss.tools.FileUtilss;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PathUtil;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.video.VideoNewCatesActivity;
import com.chookss.view.BottomListMapDialog;
import com.chookss.view.BottomListsDialog;
import com.chookss.view.GlideEngine;
import com.chookss.view.SelectDialogListener;
import com.chookss.view.listener.SelectListMapDialogListener;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.luck.picture.lib.animators.AnimationType;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lvgroup.hospital.base.BaseAct;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PublishVedioActivity extends BaseAct {
    @BindView(R.id.common_title_txt)
    TextView common_title_txt;
    @BindView(R.id.edTitle)
    EditText edTitle;
    @BindView(R.id.ivVedio)
    ImageView ivVedio;
    @BindView(R.id.edKey)
    EditText edKey;
    @BindView(R.id.edAddMyCollection)
    EditText edAddMyCollection;
    @BindView(R.id.tvMyCollection)
    TextView tvMyCollection;
    @BindView(R.id.tvChoiceCollection)
    TextView tvChoiceCollection;
    @BindView(R.id.tvDirectory)
    TextView tvDirectory;
    @BindView(R.id.tvLocation)
    TextView tvLocation;
    @BindView(R.id.tvType)
    TextView tvType;
    @BindView(R.id.tvOriginal)
    TextView tvOriginal;
    @BindView(R.id.ivBg)
    View ivBg;
    @BindView(R.id.ivChoice)
    ImageView ivChoice;
    @BindView(R.id.ivChoice2)
    ImageView ivChoice2;
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private String fileUrl, videoCollectionsCode, directoryNames, directoryCodes;
    private String compressFileUrl, videoThumbnailUrl;  //压缩后的文件地址 第一帧图片地址
    private Bitmap videoBitmap;
    private BottomListsDialog typeDialog;
    private BottomListsDialog originalDialog;
    private BottomListsDialog collectionTypeDialog;
    private BottomListMapDialog collectionDialog;
    private boolean isCompress = false;//是否压缩成功
    private boolean isStartUpload = false;//是否开始上传
    private String videoOpenStatus = "0";//0公开1私密
    private String videoOriginal = "1";//(0-否 1-是)',
    private List<Map<String, String>> colletionList = new ArrayList<>();  //创建的集合
    private List<String> collectionTypeList = new ArrayList<>();
    private int selectCollectionType = 0;//默认不选集合1创建2选择集合
    private int type = 0;//0创建1修改
    private UploadEntity.VideoBean videoBean=null;
    private int shareFlag = 1;
    private boolean uploadBegin = false;
    private boolean uploadStatus = true;//上传失败进来的需要重新上传 不缓存记录
    private String uploadTag = "";//上传失败进来的需要重新上传

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_vedio);
        ButterKnife.bind(this);
        initState();
    }

    @Override
    public void initData() {
        NavigationTools.saveUseRecord(this, "2", "10");
        common_title_txt.setText("发布");
        type = getIntent().getIntExtra("type", 0);
        uploadStatus = getIntent().getBooleanExtra("uploadStatus", true);
        List<String> stringList = new ArrayList<>();
        stringList.add("公开");
        stringList.add("自己可见");
        stringList.add("取消");
        typeDialog = new BottomListsDialog(this, stringList, new SelectDialogListener() {
            @Override
            public void onCancel() {
            }

            @Override
            public void onListItemClick(int position, List<String> list) {
                if (tvType == null) {
                    return;
                }
                if (position == 0) {
                    videoOpenStatus = "0";
                    tvType.setText("公开");
                    typeDialog.setSelect(0);
                } else if (position == 1) {
                    videoOpenStatus = "1";
                    tvType.setText("自己可见");
                    typeDialog.setSelect(1);
                }
                typeDialog.dismiss();
            }
        });
        typeDialog.setSelect(0);
        List<String> originalList = new ArrayList<>();
        originalList.add("原创");
        originalList.add("非原创");
        originalList.add("取消");
        originalDialog = new BottomListsDialog(this, originalList, new SelectDialogListener() {
            @Override
            public void onCancel() {
            }

            @Override
            public void onListItemClick(int position, List<String> list) {
                if (tvOriginal == null) {
                    return;
                }
                if (position == 0) {
                    videoOriginal = "1";
                    tvOriginal.setText("原创");
                    originalDialog.setSelect(0);
                } else if (position == 1) {
                    videoOriginal = "0";
                    tvOriginal.setText("非原创");
                    originalDialog.setSelect(1);
                }
                originalDialog.dismiss();
            }
        });
        originalDialog.setSelect(0);
        collectionTypeList.add("单个视频");
        collectionTypeList.add("创建集合");
        if (type == 1) {
            //修改视频
            videoBean = (UploadEntity.VideoBean) getIntent().getSerializableExtra("data");
            uploadTag = getIntent().getStringExtra("uploadTag");
            edTitle.setText(videoBean.getVideoTitle());
            edKey.setText(videoBean.getVideoKeyWord());
            edTitle.setText(videoBean.getVideoTitle());
            videoCollectionsCode = videoBean.getVideoCollectionsCode();
            if (Utils.isNull(videoCollectionsCode)) {
                if (!Utils.isNull(videoBean.getVideoCollectionsName())) {
//之前是创建集合， 所以有集合名称 但是没有集合code
                    edAddMyCollection.setText(videoBean.getVideoCollectionsName());
                    edAddMyCollection.setVisibility(View.VISIBLE);
                    tvMyCollection.setVisibility(View.GONE);
                    tvChoiceCollection.setText(collectionTypeList.get(1));
                    selectCollectionType = 1;
                } else {
                    //之前为单个视频
                    edAddMyCollection.setVisibility(View.GONE);
                    tvMyCollection.setVisibility(View.GONE);
                    selectCollectionType=0;
                }
            } else {
                //之前选择了集合
                tvMyCollection.setText(videoBean.getVideoCollectionsName());
                edAddMyCollection.setVisibility(View.GONE);
                tvMyCollection.setVisibility(View.VISIBLE);
                selectCollectionType=2;
            }
            directoryNames = videoBean.getCatalogNames();
            directoryCodes = videoBean.getCatalogCodes();
            if (directoryNames.contains("我的上传,")) {
                tvDirectory.setText(directoryNames.replace("我的上传,", ""));
            } else if (directoryNames.contains(",我的上传")) {
                tvDirectory.setText(directoryNames.replace(",我的上传", ""));
            } else {
                tvDirectory.setText(directoryNames);
            }
            tvLocation.setText(videoBean.getVideoLocation());
            videoOpenStatus = videoBean.getVideoOpenStatus();
            videoOriginal = videoBean.getOriginal();
            if ("1".equals(videoOpenStatus)) {
                tvType.setText("自己可见");
                typeDialog.setSelect(1);
            } else {
                tvType.setText("公开");
                typeDialog.setSelect(0);
            }
            if ("0".equals(videoOriginal)) {
                tvOriginal.setText("非原创");
                originalDialog.setSelect(1);
            } else {
                tvOriginal.setText("原创");
                originalDialog.setSelect(0);
            }
            shareFlag = Utils.changeNumber(videoBean.getShareFlag());
            if (shareFlag == 1) {
                ivBg.setVisibility(View.VISIBLE);
                ivChoice.setVisibility(View.VISIBLE);
                ivChoice2.setVisibility(View.GONE);
            } else {
                ivBg.setVisibility(View.GONE);
                ivChoice.setVisibility(View.GONE);
                ivChoice2.setVisibility(View.VISIBLE);
            }
            compressFileUrl = videoBean.getFileUrl();
            videoThumbnailUrl = videoBean.getVideoCoverPath();
            GlideUtils.load(this, videoBean.getVideoCoverPath(), ivVedio, R.drawable.default_vedios);
        } else {
            //新增视频
            String init = new ShareUtils().getString(this, StaticClass.USER_NICKNAME, "") + " " + Utils.getCurrentTime() + "的视频";
            edTitle.setText(init);
            fileUrl = getIntent().getStringExtra("fileUrl");
            directoryCodes = getIntent().getStringExtra("directoryCode");
            //默认展示自己部门目录
            if (Utils.isNull(directoryCodes)) {
                directoryNames = new ShareUtils().getString(this, StaticClass.BELG_ORG_NAME, "");
                directoryCodes = new ShareUtils().getString(this, StaticClass.BELG_CATALOG_CODE, "");
            } else {
                directoryNames = getIntent().getStringExtra("directoryName");
            }
            tvDirectory.setText(directoryNames);
            //压缩视频
            if (NetUtils.isGPSEnabled(this)) {
                compressVideo();
                getPermissions();
            } else {
                showDialog();
            }

        }

        getCollectionList();

    }
    private void showDialog() {
        new XPopup.Builder(this)
                .isDestroyOnDismiss(true)
                .dismissOnTouchOutside(false)
                .asConfirm("提示", "定位服务未开启，请打开定位服务",
                        "取消", "去开启",
                        new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivity(intent);
                                finish();
                            }
                        }, new OnCancelListener() {
                            @Override
                            public void onCancel() {
                                finish();
                            }
                        }, false)
                .show();
    }
    private void startLoc() {
        //声明LocationClient类
        try {
            if (mLocationClient == null) {
                LocationClient.setAgreePrivacy(true);
                mLocationClient = new LocationClient(getApplicationContext());
                LocationClientOption option = new LocationClientOption();
                mLocationClient.registerLocationListener(myListener);
                option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
                option.setCoorType("bd09ll");
                option.setIsNeedAddress(true);
                option.setOpenGps(true);
                option.setScanSpan(1000);
                mLocationClient.setLocOption(option);
            }
            if (mLocationClient != null) {
                mLocationClient.start();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initCollectionTypeDialog() {
        collectionTypeDialog = new BottomListsDialog(this, collectionTypeList, new SelectDialogListener() {
            @Override
            public void onCancel() {
            }

            @Override
            public void onListItemClick(int position, List<String> list) {
                if (tvChoiceCollection == null) {
                    return;
                }
                tvChoiceCollection.setText(list.get(position));
                selectCollectionType = position;
                collectionTypeDialog.setSelect(position);
                if (position == 0) {
                    edAddMyCollection.setText("");
                    videoCollectionsCode = "";
                    edAddMyCollection.setVisibility(View.GONE);
                    tvMyCollection.setVisibility(View.GONE);
                } else if (position == 1) {
                    edAddMyCollection.setText("");
                    videoCollectionsCode = "";
                    edAddMyCollection.setVisibility(View.VISIBLE);
                    tvMyCollection.setVisibility(View.GONE);
                } else if (position == 2) {
                    if (colletionList.size() > 0) {
                        tvMyCollection.setText(colletionList.get(0).get("title"));
                        videoCollectionsCode = colletionList.get(0).get("id");
                        collectionDialog.setSelect(0);
                    }
                    edAddMyCollection.setVisibility(View.GONE);
                    tvMyCollection.setVisibility(View.VISIBLE);
                }
                collectionTypeDialog.dismiss();
            }
        });
        if (1 == type) {
            if (Utils.isNull(videoCollectionsCode)) {

                if (!Utils.isNull(edAddMyCollection.getText().toString())) {
                    //之前是创建集合
                    tvChoiceCollection.setText(collectionTypeList.get(1));
                    selectCollectionType = 1;
                    collectionTypeDialog.setSelect(1);
                }else{
                    //之前为单个视频
                    tvChoiceCollection.setText(collectionTypeList.get(0));
                    selectCollectionType = 0;
                    collectionTypeDialog.setSelect(0);
                }

            } else {
                //之前选择了集合
                selectCollectionType = 2;
                collectionTypeDialog.setSelect(2);
                tvChoiceCollection.setText(collectionTypeList.get(2));
            }
        }
    }

    private void initCollectionDialog() {
        collectionDialog = new BottomListMapDialog(this, colletionList, new SelectListMapDialogListener() {
            @Override
            public void onCancel() {

            }

            @Override
            public void onListItemClick(int position, List<Map<String, String>> list) {

                if (tvMyCollection == null) {
                    return;
                }
                if (position == list.size() - 1) {

                } else {
                    tvMyCollection.setText(list.get(position).get("title"));
                    videoCollectionsCode = list.get(position).get("id");
                    collectionDialog.setSelect(position);
                }
                collectionDialog.dismiss();
            }
        });
        if (1 == type && !Utils.isNull(videoCollectionsCode)) {
            for (int i = 0; i < colletionList.size(); i++) {
                if (videoCollectionsCode.equals(colletionList.get(i).get("id"))) {
                    collectionDialog.setSelect(i);
                }
            }
        } else {
            collectionDialog.setSelect(0);
        }


    }

    private void getPermissions() {
        XXPermissions.with(this)
                // 申请单个权限
                .permission(Permission.ACCESS_FINE_LOCATION)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            startLoc();
                        } else {
                            MyToast.show("定位权限未正常授予");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            MyToast.show("被永久拒绝授权，请手动授予定位权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(PublishVedioActivity.this, permissions);
                        } else {
                            MyToast.show("获取定位权限失败");
                        }
                    }
                });
    }

    private void compressVideo() {
        //压缩代码放后台执行
        compressFileUrl = fileUrl;
        isCompress = true;
        videoThumbnailUrl = getExternalFilesDir(Urls.UPLOADVIDEO).getAbsolutePath() + File.separator + System.currentTimeMillis() + ".JPEG";
        Uri vedioUri = null;
        File vedio = new File(fileUrl);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            vedioUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileProvider", vedio);
        } else {
            vedioUri = Uri.fromFile(vedio);
        }
        videoBitmap = FileUtilss.getVideoThumb(this, vedioUri);
        Glide.with(this).load(videoBitmap).into(ivVedio);
        FileUtilss.saveBitmap2(videoBitmap, videoThumbnailUrl);
    }

    private void upLoadData() {
        Intent intent = new Intent(this, UploadFileService.class);
        if (edTitle == null) {
            return;
        }
        //往service传值所用
        UploadEntity newUploadEntity = new UploadEntity();
        UploadEntity.VideoBean videoEntity = new UploadEntity.VideoBean();
        videoEntity.setId("");
        videoEntity.setVideoId("");
        videoEntity.setVideoTitle(edTitle.getText().toString());
        videoEntity.setVideoKeyWord(edKey.getText().toString());
        videoEntity.setVideoCoverPath(videoThumbnailUrl);
        videoEntity.setFileUrl(compressFileUrl);
        videoEntity.setVideocompress(compressFileUrl);
        if (selectCollectionType == 0) {
            videoEntity.setVideoCollectionsName("");
            videoEntity.setVideoCollectionsCode("");
        } else if (selectCollectionType == 1) {
            videoEntity.setVideoCollectionsName(edAddMyCollection.getText().toString());
            videoEntity.setVideoCollectionsCode("");
        } else if (selectCollectionType == 2) {
            videoEntity.setVideoCollectionsName(tvMyCollection.getText().toString());
            videoEntity.setVideoCollectionsCode(videoCollectionsCode);
        }
        videoEntity.setVideoOpenStatus(videoOpenStatus);
        videoEntity.setCatalogCodes(directoryCodes);
        videoEntity.setCatalogNames(directoryNames);
        videoEntity.setOriginal(videoOriginal);
        videoEntity.setVideoLocation(tvLocation.getText().toString());
        videoEntity.setShareFlag(shareFlag + "");

        if (uploadStatus) {
            newUploadEntity.setUploadStatus(1);
            newUploadEntity.setUploadTag(Utils.getCurrentTime2());
        } else {
            newUploadEntity.setUploadStatus(2);
            newUploadEntity.setUploadTag(uploadTag);
        }
        if(videoBean!=null){
            videoEntity.setProvideEmployeeCode(videoBean.getProvideEmployeeCode());
            videoEntity.setProvideEmployeeName(videoBean.getProvideEmployeeName());
        }else{
            newUploadEntity.setProvideEmployeeCode(new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, ""));
            newUploadEntity.setProvideEmployeeName(new ShareUtils().getString(this, StaticClass.USER_NICKNAME, ""));
        }
        newUploadEntity.setVideo(videoEntity);
        newUploadEntity.setResourceType("3");
        newUploadEntity.setUploadTitle(edTitle.getText().toString());

        intent.putExtra("data", newUploadEntity);
        intent.putExtra("resourceType", "3");
        startService(intent);
//        MyToast.show("正在上传...");
        KLog.i(compressFileUrl);
        KLog.i(edTitle.getText().toString());
        KLog.i(edKey.getText().toString());
        KLog.i(videoThumbnailUrl);
        KLog.i(videoCollectionsCode + "===");
        KLog.i(edAddMyCollection.getText().toString() + "==");
        KLog.i(tvMyCollection.getText().toString() + "==---");
        KLog.i(videoOpenStatus);
        KLog.i(directoryCodes);
        KLog.i(tvLocation.getText().toString());
        uploadBegin = false;
        finish();
    }

    private void getCollectionList() {
        MyHttpRequest.postRequest(Urls.getCollectionList, this, SignUtils2.makeSignStr(null), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            Map<String, String> map = new ArrayMap<>();
                            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                            map.put("id", jsonObject1.getString("collectionsCode"));
                            map.put("title", jsonObject1.getString("collectionsName"));
                            colletionList.add(map);
                        }
                        if (jsonArray.length() > 0) {
                            Map<String, String> map = new ArrayMap<>();
                            map.put("id", "");
                            map.put("title", "取消");
                            colletionList.add(map);
                            collectionTypeList.add("选择已有集合");
                            initCollectionDialog();
                        }
                        initCollectionTypeDialog();

                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    initCollectionTypeDialog();
                    e.printStackTrace();
                }
            }
        });

    }

    private void editData() {
        if (edTitle == null) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("id", videoBean.getId());
        map.put("videoTitle", edTitle.getText().toString());
        map.put("videoId", videoBean.getVideoId());
        map.put("videoKeyWord", edKey.getText().toString());
        map.put("videoCoverPath", videoBean.getVideoCoverPath());
        if (selectCollectionType == 0) {
            map.put("videoCollectionsCode", "");
            map.put("videoCollectionsName", "");
        } else if (selectCollectionType == 1) {
            map.put("videoCollectionsCode", "");
            map.put("videoCollectionsName", edAddMyCollection.getText().toString());
        } else if (selectCollectionType == 2) {
            map.put("videoCollectionsCode", videoCollectionsCode);
            map.put("videoCollectionsName", tvMyCollection.getText().toString());
        }
        map.put("videoOpenStatus", videoOpenStatus);
        map.put("original", videoOriginal);
        map.put("videoAuditStatus", "0");
        map.put("catalogCodes", directoryCodes);
        map.put("videoLocation", tvLocation.getText().toString());
        map.put("shareFlag", shareFlag + "");
        map.put("provideEmployeeCode", videoBean.getProvideEmployeeCode());
        map.put("provideEmployeename", videoBean.getProvideEmployeeName());
        MyHttpRequest.postRequest(Urls.updateAppVideoById, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        EventBus.getDefault().post(new MyEvent("RefreshVideo"));
                        MyToast.show("视频修改成功");
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    MyToast.show("视频修改失败，请稍后重试");
                }
                finish();
            }
        });
    }

    private void choiceVedio() {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            PictureSelector.create(PublishVedioActivity.this)
                                    .openGallery(SelectMimeType.ofVideo())
                                    .isDisplayCamera(true)//是否显示相机入口
                                    .setMaxVideoSelectNum(1)
                                    .setMaxSelectNum(1)
                                    .setSelectionMode(SelectModeConfig.SINGLE)//单选
                                    .isPreviewVideo(true)//是否支持预览视频
                                    .setSelectMinFileSize(50)//过滤最小文件50k
                                    .setFilterVideoMaxSecond(600)//过滤最大视频选择600s
                                    .setRecordVideoMaxSecond(30)//过滤录制最大30s
                                    .isFilterSizeDuration(true)//是否过滤图片或音视频大小时长为0的资源
                                    .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)
                                    .setImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                    .forResult(PictureConfig.REQUEST_CAMERA);
                        } else {
                            PermissionUtils.errorPermission(PublishVedioActivity.this, granted, all);
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(PublishVedioActivity.this, denied, quick);
                    }
                });
    }


    @OnClick({R.id.common_title_back, R.id.rlChoice, R.id.tvOriginal, R.id.tvMyCollection, R.id.ivVedio, R.id.tvChoiceCollection, R.id.tvChoieDirectory, R.id.tvChoieLocation, R.id.tvType, R.id.tv_publish})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                if (uploadBegin) {
                    MyToast.show("视频发布中");
                } else {
                    finish();
                }
                break;
            case R.id.rlChoice:
                if (ivBg == null) {
                    return;
                }
                if (shareFlag == 1) {
                    shareFlag = 0;
                    ivBg.setVisibility(View.GONE);
                    ivChoice.setVisibility(View.GONE);
                    ivChoice2.setVisibility(View.VISIBLE);
                } else {
                    shareFlag = 1;
                    ivBg.setVisibility(View.VISIBLE);
                    ivChoice.setVisibility(View.VISIBLE);
                    ivChoice2.setVisibility(View.GONE);
                }
                break;
            case R.id.ivVedio:
                if (1 == type) {
                    choiceVedio();
                }
                break;
            case R.id.tvChoiceCollection:
                if (collectionTypeDialog != null) {
                    collectionTypeDialog.show();
                }
                break;
            case R.id.tvMyCollection:
                if (selectCollectionType == 2) {
                    if (collectionDialog != null) {
                        collectionDialog.show();
                    }
                }
                break;
            case R.id.tvChoieDirectory:
                Intent intent = new Intent(this, VideoNewCatesActivity.class);
                intent.putExtra("videoType", "3");
                startActivity(intent);
                break;
            case R.id.tvChoieLocation:
                getPermissions();
                break;
            case R.id.tvType:
                if (typeDialog != null) {
                    typeDialog.show();
                }
                break;
            case R.id.tvOriginal:
                if (originalDialog != null) {
                    originalDialog.show();
                }
                break;
            case R.id.tv_publish:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (edAddMyCollection == null) {
                    return;
                }
                if (Utils.isNull(edTitle.getText().toString().replace(" ", ""))) {
                    MyToast.show("请输入标题");
                    return;
                }

                if (selectCollectionType == 1) {
                    if (Utils.isNull(edAddMyCollection.getText().toString())) {
                        MyToast.show("请创建集合");
                        return;
                    }
                } else if (selectCollectionType == 2) {
                    if (colletionList.size() > 0 && Utils.isNull(tvChoiceCollection.getText().toString())) {
                        MyToast.show("请选择集合");
                        return;
                    }
                }
                if (Utils.isNull(tvDirectory.getText().toString())) {
                    MyToast.show("请选择所属目录");
                    return;
                }
                if (1 == type) {
//                    修改视频
                    if (!uploadStatus) {
                        //上传失败进来的
                        upLoadData();
                    } else {
                        //修改视频但是没有动视频直接上传
                        showLoading();
                        editData();
                    }
                } else {
                    //第一次上传
                    if (isCompress) {
                        upLoadData();
                    } else {
                        uploadBegin = true;
                        isStartUpload = true;
                        showLoading();
                    }
                }

                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (uploadBegin) {
            MyToast.show("视频上传中");
        } else {
            super.onBackPressed();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
            if (map.containsKey("videoCate") && map.containsKey("videoNames")) {
                if (tvDirectory == null) {
                    return;
                }
                directoryNames = map.get("videoNames");
                directoryCodes = map.get("videoCate");
                tvDirectory.setText(directoryNames);
            }
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.REQUEST_CAMERA) {
                // 如果是直接从相册获取
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);

                KLog.i("压缩::" + selectList.get(0).getCompressPath());
                KLog.i("原图::" + selectList.get(0).getPath());
                if (selectList.get(0).getPath().contains("content://")) {
                    Uri uri = Uri.parse(selectList.get(0).getPath());
                    fileUrl = PathUtil.getPath(this, uri);
                } else {
                    fileUrl = selectList.get(0).getPath();
                }
                //压缩视频
                compressVideo();
            }
        }
    }

    private int locationFlag = 0;
    private boolean firstLocation=true;
    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location != null) {
                locationFlag++;
                if (tvLocation == null) {
                    return;
                }
                if (!Utils.isNull(location.getAddrStr())) {
                    tvLocation.setText(location.getAddrStr());
                }else {
                    if(firstLocation){
                        if (mLocationClient != null) {
                            firstLocation=false;
                            mLocationClient.start();
                        }
                    }
                }
                if (locationFlag > 6) {
                    if (null != mLocationClient && mLocationClient.isStarted()) {
                        locationFlag = 0;
                        if (mLocationClient != null) {
                            mLocationClient.stop();
                        }
                    }
                }
            }else {
                if(firstLocation){
                    if (mLocationClient != null) {
                        firstLocation=false;
                        mLocationClient.start();
                    }
                }
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (videoBitmap != null) {
                videoBitmap.recycle();
            }
            if (mLocationClient != null) {
                mLocationClient.stop();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
